<?php


namespace app\wechat\controller;


use app\BaseController;
use app\common\model\Book;
use app\common\model\User;
use app\common\model\Coupon;
use app\common\model\UserEmpiricalList;
use app\common\model\UserLevel;
use app\Request;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use think\cache\driver\Redis;
use think\exception\ValidateException;
use think\facade\Db;

class Mine extends AuthBase
{
     protected $noLogin = ['homepage'];
//     public $userId = 10;

    public function index()
    {
        $user=Db::name('user')
            ->where('id',$this->userId)
            ->field('id,nickname,head_img,is_vip,asset_price,sell_price')
            ->find();
        $count=Db::name('family_member')
            ->where('user_id',$this->userId)
            ->count();
        if (!$count){
            return show(-2,'');
        }
        $user['money']=$user['asset_price']-$user['sell_price'];
        $user['vip_price']=8;
        $user['vip_price_yuanjia']=18;
        $data['user']=$user;
        $data['sum_goods']=Db::name('goods')
            ->where('user_id',$this->userId)
            ->count();
        $data['fuyi_goods']=Db::name('goods')
            ->where('user_id',$this->userId)
            ->where('status',1)
            ->count();
        $data['tuiyi_goods']=Db::name('goods')
            ->where('user_id',$this->userId)
            ->where('status',2)
            ->count();
        return $this->show(1, '', $data);
    }
    /**
     * 修改头像
     */
    public function edit_info(){
        $head_img=input('post.head_img');
        $nickname=input('post.nickname');
        $res=Db::name('user')
            ->where('id',$this->userId)
            ->update(['head_img'=>$head_img,'nickname'=>$nickname,'update_time'=>time()]);
        if (!$res){
            return $this->show(0,'修改失败');
        }
        return $this->show(1,'修改成功');
    }
    /**
     * 购买会员
     */
    public function go_pay(){
        $data = input('post.');
        $user = Db::name('user')
            ->where('id', $this->userId)
            ->find();
        // 启动事务
        Db::startTrans();
        try {
            $out_trade_no = $this->order_number($user['openid']);
            //创建订单
            Db::name('order')
                ->insert(['name'=>'购买会员','out_trade_no'=>$out_trade_no,'user_id'=>$this->userId,'price'=>8,'status'=>0,
                    'create_time'=>time(),'update_time'=>time(),'token'=>$this->request->header("token")]);
            $res = $this->Pay(8, $user['openid'], '购买会员', $out_trade_no);
            Db::commit();
            return show(1, '订单提交成功', $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show(0, '订单提交失败');
        }
    }
    /**
     * 小程序支付
     */
    public function Pay($fees, $openids, $bodys, $out_trade_nos)
    {
        $config = [
            'token' => '',
            'appid' => 'wx5436887e100ceeff',
            'appsecret' => 'f21e22bb42f395cb121b030dab0a51ff',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => "1607822533",
            'mch_key' => '27f16add8345d9a76f9ca68c8e02a497',
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => '',
            'ssl_cer' => '',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path' => '',
        ];


        // 创建接口实例
        $wechat = new \WeChat\Pay($config);

        // 组装参数，可以参考官方商户文档
        $options = [
            'body' => $bodys,
            'out_trade_no' => $out_trade_nos,
            'total_fee' => $fees * 100,
            'openid' => $openids,
            'trade_type' => 'JSAPI',
            'notify_url' => 'https://goods.farmhelper.top/wechat/pay/notify',
            'spbill_create_ip' => '82.156.114.203',
        ];

        try {

            // 生成预支付码
            $result = $wechat->createOrder($options);

            // 创建JSAPI参数签名
            $options = $wechat->createParamsForJsApi($result['prepay_id']);
            return $options;
            // @todo 把 $options 传到前端用js发起支付就可以了

        } catch (\Exception $e) {

            // 出错啦，处理下吧
            echo $e->getMessage() . PHP_EOL;
        }
    }

    //随机32位字符串
    private function nonce_str()
    {
        $result = '';
        $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
        for ($i = 0; $i < 32; $i++) {
            $result .= $str[rand(0, 48)];
        }
        return $result;
    }

    //生成订单号
    private function order_number($openid)
    {
        //date('Ymd',time()).time().rand(10,99);//18位
        return md5($openid . time() . rand(10, 99)); //32位
    }

    //签名 $data要先排好顺序
    private function sign($data)
    {
        $stringA = '';
        foreach ($data as $key => $value) {
            if (!$value) continue;
            if ($stringA) $stringA .= '&' . $key . "=" . $value;
            else $stringA = $key . "=" . $value;
        }
        $wx_key = '27f16add8345d9a76f9ca68c8e02a497';
        $stringSignTemp = $stringA . '&key=' . $wx_key; //申请支付后有给予一个商户账号和密码，登陆后自己设置key
        return strtoupper(md5($stringSignTemp));
    }

    //curl请求啊
    function http_request($url, $data = null, $headers = array())
    {
        $curl = curl_init();
        if (count($headers) >= 1) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //获取xml
    private function xml($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = "";
        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }
}
